<?php

/*
 * author:Jackli
 * data:2016年3月30号
 * 用来显示和处理微信信息
*/

class WeixinloginController extends \Core_BaseCtl
{
    //文件缓存
    public $cache;

    //初始化
    public function init()
    {
        parent::init();
        //缓存开启
        $cache_config = $this->config['cache'];
        $this->cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
    }

    //通过code获取临时的access_token
    public function getTokenByCode()
    {
        $appId = $this->getAppInfo();
        $secret = $this->getAppSecret();

        $ac_flag = $this->cache->get('access_token');
        $re_flag = $this->cache->get('refresh_token');

        if (!$ac_flag && $re_flag) {
            //die('刷新');
            //$access_token不存在，$re_flag存在
            $res = $this->refreshAccessToken();

            return $res;
        } elseif ((!$ac_flag && !$re_flag) || $ac_flag) {
            //通过code获取临时的access_token
            //die('重新获取');
            $code = Tools_help::getSession('code');
            //grant_type
            $grant_type = 'authorization_code';
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$secret&code=$code&grant_type=$grant_type";
            //访问获取json数据
            $result = Tools_help::weixinCurlGet($url);
            //转换
            $data_obj = json_decode($result);
            if (isset($data_obj->errcode)) {
                $content = '服务器出错';
                $url = '/mobileregister/login';
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                exit;
            }
            //记录
            $this->cache->set('access_token', $data_obj->access_token, $data_obj->expires_in - 1500);
            $this->cache->set('refresh_token', $data_obj->refresh_token);
            //用户openid
            //$this->cache->set('openid', $data_obj->openid);
            Tools_help::setSession('openid', $data_obj->openid);
            if ($this->cache->get('access_token')) {
                return true;
            } else {
                return false;
            }
        }
//        elseif ($ac_flag) {
//            //die('不用获取');
//            return true;
//        }
    }

    //通过code获取临时的access_token
    public function getTokenSlientByCode()
    {
        $appId = $this->getAppInfo();
        $secret = $this->getAppSecret();

        $ac_flag = $this->cache->get('access_token');

//        if (!$ac_flag) {
        //通过code获取临时的access_token
        //die('重新获取');
        $code = Tools_help::getSession('code');
        //grant_type
        $grant_type = 'authorization_code';
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$secret&code=$code&grant_type=$grant_type";
        //访问获取json数据
        $result = Tools_help::weixinCurlGet($url);
        //转换
        $data_obj = json_decode($result);
        if (isset($data_obj->errcode)) {
            $content = '服务器出错';
            $url = '/mobileregister/login';
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            exit;
        }
        //记录
        $this->cache->set('access_token', $data_obj->access_token, $data_obj->expires_in);
        //用户openid

        $this->cache->set('openid', $data_obj->openid);
        if ($this->cache->get('access_token')) {
            return true;
        } else {
            return false;
        }
//        }
//        elseif ($ac_flag) {
//            //die('不用获取');
//            return true;
//        }
    }

    //微信授权登陆回调方法
    public function redirectAction()
    {
        if (isset($_GET['code'])) {
            // 获取回调code
            $code = $this->getg('code');
        } else {
            $content = 'code获取失败，请稍后再试';
            $url = '/mobileregister/login';
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            exit;
        }
        //检查是否存在缓存
        Tools_help::setSession('code', $code);

        $this->redirect(Tools_help::url('weixinlogin/printUser'));
        exit;
    }

    //利用手机号进行微信回调
    public function mobileRedirectAction()
    {
        if (isset($_GET['code'])) {
            // 获取回调code
            $code = $this->getg('code');
        } else {
            $content = 'code获取失败，请稍后再试';
            $url = '/mobileregister/login';
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            exit;
        }
        Tools_help::setSession('code', $code);

        $phonenum = $this->getg('phonenum');

        $this->redirect(Tools_help::url("weixinlogin/printmuser?phonenum=$phonenum"));
        exit;
    }

    //用于打印用户信息
    public function printUserAction()
    {
        if ($this->getTokenByCode()) {
            //获取用户信息
            //$openId = $this->cache->get('openid');
            $openId = Tools_help::getSession('openid');
            if (!$openId) {
                //$opinID没有数据数据,再次获取openid
                $this->getTokenByCode();
            }
            //检查用户是否已经存在
            $user = new WxuserModel();
            $flag = $user->checkWUserExist($openId);

            if ($flag) {
                //echo '之前已经登录过，正为你跳转';
                //设置session回收时间

                ini_set('session.gc_maxlifetime', 60);

                Tools_help::setSession('openid', $flag['openid']);

                $content = '之前已经登录过，正为你跳转';
                $url = '/mobileregister/userinfo/id/' . $flag['id'];
                $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));

                exit;
            } else {
                //拉取信息，入库
                $this->fetchUserInfo($openId);
            }
        } else {
            echo 'access 出错，好好加油吧';
            exit;
        }
    }

    //用于打印手机+微信用户
    public function printMUserAction()
    {
        $phonenum = $this->getg('phonenum');

        if ($this->getTokenSlientByCode()) {
            //获取用户信息
            $openId = $this->cache->get('openid');
            //检查用户是否已经存在
            $user = new WxuserModel();
            $flag = $user->checkMWUserExist($openId, $phonenum);
            if ($flag) {
                //echo '之前已经登录过，正为你跳转';
                //设置session回收时间
                ini_set('session.gc_maxlifetime', 1);
                Tools_help::setSession('openid', $flag['openid']);

//                $content = '之前已经登录过，正为你跳转';
//                $url = '/mobileregister/userinfo/id/' . $flag['id'];
//                $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));
                $this->redirect(Tools_help::url('mobileregister/userinfo?id=' . $flag['id']));
                exit;
            } else {
                //拉取信息，入库
                $this->fetchMUserInfo($openId, $phonenum);
            }
        } else {
            echo 'access 出错，好好加油吧';
            exit;
        }
    }

    //利用refresh_token 刷新token的有效时间
    public function refreshAccessToken()
    {
        //获取appid
        $appId = $this->getAppInfo();
        //grant_type用户刷新时长
        $grant_type = 'refresh_token';

        $refresh_token = $this->cache->get('refresh_token');
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appId&grant_type=$grant_type&refresh_token=$refresh_token";

        //访问获取json数据
        $result = Tools_help::weixinCurlGet($url);
        //转换
        $data_obj = json_decode($result);

        if (!isset($data_obj->errcode)) {
            //返回正常
            //access_token更新有效时间
            $this->cache->set('access_token', $data_obj->access_token, $data_obj->expires_in - 1500);
            //refresh_token
            $this->cache->set('refresh_token', $data_obj->refresh_token);
            return true;
        } else {
            return false;
        }
    }

    //拉取用户具体信息
    public function fetchUserInfo($openId)
    {
        //获取当前access_token
        $access_token = $this->cache->get('access_token');
        if ($access_token) {
            //url
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";

            //访问获取json数据
            $result = Tools_help::weixinCurlGet($url);
            //转换
            $userInfo_obj = json_decode($result);
            if (isset($userInfo_obj->errcode)) {
                $content = '获取远程信息失败，请稍后再试';
                $url = '/mobileregister/login';
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                exit;
            }

            //接下来可以拉取用户信息进行入库
            //格式如下
            $user = new WxuserModel();
            $insertId = $user->recordWxUserInfo($userInfo_obj);

            if ($insertId) {
                //设置session回收时间
                ini_set('session.gc_maxlifetime', 60);
                Tools_help::setSession('openid', $openId);

                $content = '登录成功';
                $url = '/mobileregister/userinfo/id/' . $insertId;
                $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));
                //$this->redirect(Tools_help::url('mobileregister/userinfo?id=' . $insertId));
                exit;
            } else {
                $content = '登录失败，请重试';
                $url = '/mobileregister/login';
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                exit;
            }
        } else {
            $content = '获取token信息失败，请稍后再试';
            $url = '/mobileregister/login';
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            exit;
        }
    }

    //静默登录，拉取用户openid
    public function fetchMUserInfo($openId, $phonenum)
    {
        //记录用户openid和phonenum信息进行入库
        //格式如下
        $user = new WxuserModel();
        $insertId = $user->recordMWxUserInfo($openId, $phonenum);

        if ($insertId) {
            //'登录成功'
            //设置session回收时间
            ini_set('session.gc_maxlifetime', 1);
            Tools_help::setSession('openid', $openId);

            $content = '登录成功';
            $url = '/mobileregister/userinfo/id/' . $insertId;
            $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));
            exit;
        } else {
            //'登录失败，请重试'
            $content = '登录失败，请重试';
            $url = '/mobileregister/login';
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            exit;
        }
    }

    //获取公众号的app信息
    public function getAppInfo()
    {
        //获取微信账号信息
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        if (isset($config['wechat'])) {
            $appId = $config['wechat']['appid'];
            return $appId;
        } else {
            return null;
        }
    }

    //获取公众号secret信息
    public function getAppSecret()
    {
        //获取微信账号信息
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        if (isset($config['wechat'])) {
            $appSecret = $config['wechat']['appsecret'];
            return $appSecret;
        } else {
            return null;
        }
    }
}
